<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/14
 * Time: 14:34
 */
namespace app\common;

use think\Controller;
use think\Db;

class Common extends Controller
{


    /**
     * 判断字段是否在数组中存在
     * @param array $base
     * @param array $child
     * @return int
     */
    public static function checkFields(array $base, array $child)
    {
        foreach ($child as $v) {
            if (!in_array(strtolower($v), $base)) {
                return config('f_code');
            }
        }
        return config('t_code');
    }

    /**
     * 获取数组的键或者值
     * @param array $array
     * @param string $type
     * @return array
     */
    public static function getKeyArray(array $array, $type)
    {
        $keys = [];
        $t = $type == 'k' ? 'k' : 'v';
        foreach ($array as $k => $v) {
            $keys[] = strtolower($$t);
        }
        return $keys;
    }

    /**
     * 连接数组 转换为字符串
     * @param array $array | 要连接的数组
     * @param string $joiner | key value 连接符
     * @param string $connect | 间隔符
     * @param string $prefix | 前缀
     * @return string
     */
    public static function spliceArray(array $array, $prefix = '', $joiner = ' ', $connect = ',')
    {
        if (empty($array)) {
            return '';
        }
        $str = '';
        foreach ($array as $k => $v) {
            $str = $str . $prefix . $k . $joiner . $v . $connect;
        }
        $str = rtrim($str, $connect);
        $str = ltrim($str, ' ');
        return $str;
    }

    /**
     * 校验页码数
     * @param $page
     * @param $pre
     * @return array
     */
    public static function checkPageAndPre($page, $pre)
    {
        if (!is_numeric($pre) || !is_numeric($page)) {
            return ['code' => config('f_code'), 'msg' => '页码数或页码条数必须为数字'];
        }
        if ($pre <= 0 || $page <= 0) {
            return ['code' => config('f_code'), 'msg' => '页码数或页码条数不正确'];
        }
        return ['code' => config('t_code')];
    }

    /**
     * 校验排序
     * @param null $baseSort | 基本排序字段
     * @param array $sort |  需校验的排序字段
     * @param null $baseType |   基本排序方法
     * @return array
     */
    public static function checkSortCondition($baseSort = null, array $sort = [], $baseType = null)
    {
        if ((!isset($baseSort) || empty($sort))
            &&
            (!isset($baseType))
        ) {
            return ['code' => config('f_code'), 'msg' => '请求参数错误'];
        } else if (!isset($baseSort) || empty($sort)) {
            if (self::checkFields($baseType, self::getKeyArray($sort, 'v')) == config('f_code')) {
                return ['code' => config('f_code'), 'msg' => '不存在此排序方法'];
            }
        } else if (!isset($baseType)) {
            if (Common::checkFields($baseSort, self::getKeyArray($sort, 'k')) == config('f_code')) {
                return ['code' => config('f_code'), 'msg' => '不存在此排序字段'];
            }
        } else {
            if (self::checkFields($baseType, self::getKeyArray($sort, 'v')) == config('f_code')) {
                return ['code' => config('f_code'), 'msg' => '不存在此排序方法'];
            }
            if (Common::checkFields($baseSort, self::getKeyArray($sort, 'k')) == config('f_code')) {
                return ['code' => config('f_code'), 'msg' => '不存在此排序字段'];
            }
        }
        return ['code' => config('t_code')];
    }

    /**
     * 校验数字是否大于0 并且是整数
     * @param $id |校验的id
     * @param $status
     * @return bool
     */
    public static function checkNumber($id, $status = 1)
    {
        if ($status == 1) {
            if ($id <= 0 || !is_numeric($id) || floor($id) != $id) {
                return false;
            }
            return true;
        } else {
            if ($id < 0 || !is_numeric($id) || floor($id) != $id) {
                return false;
            }
            return true;
        }
    }


    /**
     * 判断字段是否存在表中
     * 不存在返回400  存在返回200
     * @param $table_name
     * @param $value
     * @param string $fields
     * @return int
     */
    public static function checkTableFields($table_name, $fields, $value)
    {
        $res = Db::table($table_name)
            ->field($fields)
            ->where([
                $fields => $value
            ])->find();
        return empty($res) ? config('f_code') : config('t_code');
    }

    /**
     * 判断字段是否存在表中
     * 不存在返回400  存在返回200
     * @param $table_name
     * @param $value
     * @param string $fields
     * @param string $str
     * @param string $whereName
     * @return int
     */
    public static function checkTableFieldsValue($table_name, $fields, $whereName, $value, $str)
    {

        $res = Db::table($table_name)
            ->field($fields)
            ->where([
                $whereName => $value
            ])->find();

        if (empty($res)) {
            return config('f_code');
        } else {
            return $res[$fields] == $str ? config('t_code') : $res[$fields] == 0 ? config('t_code') : config('f_code');
        }
    }


    /**
     * 获取表中字段
     * @param $table_name
     * @param $fields
     * @param $whereName
     * @param $value
     * @return mixed
     */
    public static function getTableValue($table_name, $fields, $whereName, $value)
    {

        if (is_array($whereName)) {
            $where = '';
            foreach ($whereName as $k => $v) {
                $where = $where . ' ' . $v . ' = "' . $value[$k] . '" and';
            }
            $where = rtrim($where, 'and');
            $res = Db::table($table_name)
                ->field($fields)
                ->where($where)
                ->find();
        } else {
            $res = Db::table($table_name)
                ->field($fields)
                ->where([
                    $whereName => $value
                ])->find();
        }
        if (is_array($fields)) {
            return $res;
        } else {
            return $res[$fields];
        }
    }

    public static function tableValue($table_name, $fields, $whereName, $value)
    {
        $where = '';
        foreach ($whereName as $k => $v) {
            $where = $where . ' ' . $v . ' = "' . $value[$k] . '" and';
        }
        $where = rtrim($where, 'and');
        $res = Db::table($table_name)
            ->field($fields)
            ->where($where)
            ->find();
        return $res;
    }

    /**
     * 校验字符串长度
     * 键| 校验内容的名字   值 为数组|"最小长度,最大长度",需要校验的内容
     * @param array $arr
     * @return array
     */
    public static function checkLength(array $arr = ['文章内容' => ['10,100', '内容内容内容']])
    {

        foreach ($arr as $k => $v) {
            $len = explode(',', $v[0]);
            $lenMin = $len[0];//最小长度
            $lenMax = $len[1];//最大长度
            $len = mb_strlen($v[1]);//获取校验内容的长度
            if ($len > $lenMax || $len < $lenMin) {
                return ['code' => config('f_code'), 'msg' => "{$k}长度区间为{$lenMin}--{$lenMax}"];
            }
        }
        return ['code' => config('t_code')];
    }

    /**
     * 校验字符串
     * @param $name
     * @param $max
     * @param $min
     * @param $msg
     * @return array
     */
    public static function checkName($name, $max, $min, $msg)
    {
        $nameLength = mb_strlen($name);
        if ($nameLength > $max || $nameLength < $min) {//校验标题长度
            return [
                'code' => config('f_code'),
                'msg' => "{$msg}最少{$min}个字,最多{$max}个字"
            ];
        }
        $config_name = trim($name);
        if (empty($config_name)) {
            return ['code' => config('f_code'), 'msg' => $msg . '不能为空'];
        }
        return ['code' => config('t_code')];
    }


    /**
     * 校验手机号
     * @param $tel
     * @return bool
     */
    public static function checkTel($tel)
    {
        // 验证联系电话  手机
        $is_mob = "/^1[345789]{1}\d{9}$/";

        //座机
        $is_tel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";

        if (!preg_match($is_mob, $tel) && !preg_match($is_tel, $tel)) {
            return false;
        } else {
            return true;
        }
    }


    public function updateImg(array $arr = ['shop_logo', 'shop_bg', 'record_img' => ['license_img', 'legal_id_img', 'other_img']])
    {
        $file = $_FILES;
        $err = [];//存放错误信息
        $data = [];//存放上传成功的图片
        foreach ($arr as $k => $v) {
            $title = $v;
            if (is_array($v)) {//接受的数组图片
                $title = $k;
                if (!array_key_exists($title, $file)) {
                    continue;
                }
                $img = $file[$title]['tmp_name'];
                foreach ($img as $kk => $vv) {
                    if ($file[$title]['error'][$kk] != 0) {
                        $err[] = [
                            'code' => config('f_code'),
                            'data' => $file[$title]['name'][$kk],
                            'msg' => $this->Err($file[$title]['error'][$kk])//获取错误信息
                        ];
                    } else {
                        $res = $this->moveImg($vv, $file[$title]['name'][$kk]);
                        if ($res['code'] != config('t_code')) {
                            $err[] = $res;
                        } else {
                            $data[$title][$v[$kk]] = $res['data'];
                        }
                    }
                }
            } else {//接受的单张上传图片
                if (!array_key_exists($title, $file)) {
                    $data[$title] = '';
                    continue;
                }
                if ($file[$title]['error'] != 0) {
                    $err[] = [
                        'code' => config('f_code'),
                        'data' => $file[$title]['name'],
                        'msg' => $this->Err($file[$title]['error'])//获取错误信息
                    ];
                } else {
                    $res = $this->moveImg($file[$title]['tmp_name'], $file[$title]['name']);
                    if ($res['code'] != config('t_code')) {
                        $err[] = $res;
                    } else {
                        $data[$title] = $res['data'];
                    }
                }
            }
        }
        return ['data' => $data, 'err' => $err];
    }

    /**
     * 判断文件上传的error信息
     * @param $err
     * @return string
     */
    protected function Err($err)
    {
        switch ($err) {
            case 1:// 文件大小超出了服务器的空间大小
                $str = "The file size is beyond the server's space size";
                break;
            case 2:// 要上传的文件大小超出浏览器限制
                $str = "The file is too large";
                break;
            case 3:// 文件仅部分被上传
                $str = "The file was only partially uploaded";
                break;
            case 4:// 没有找到要上传的文件
                $str = "Did not find the file to upload";
                break;
            case 5:// 服务器临时文件夹丢失
                $str = "The server temporary folder is missing";
                break;
            case 6:// 文件写入到临时文件夹出错
                $str = "The file was written to a temporary folder error";
                break;
            default :
                $str = "非法操作";
                break;
        }
        return $str;
    }

    /**
     * 移动临时图片
     * @param $img_name
     * @param $name
     * @param $file
     * @param array $exc
     * @return array|string
     */
    private function moveImg($img_name, $name, $exc = ['jpg', 'jpeg', 'png'], $file = 'img')
    {
        $suffix = strripos($name, '.');
        $suffix = substr($name, $suffix + 1);//截取图片类型
        $suffix = strtolower($suffix);
        if (!in_array($suffix, $exc)) {
            return ['code' => config('f_code'), 'data' => $name, 'msg' => '数据类型格式错误'];
        }
        $dir = date('Ymd', time());//保存图片的文件夹
        $save_name = uniqid() . '.' . $suffix;
        //判断img文件夹是否存在  不存在就创建
        if (!file_exists(ROOT_PATH . 'public' . DS . $file)) {
            $oldUMask = umask(0);
            mkdir(ROOT_PATH . 'public' . DS . $file, 0777);
            umask($oldUMask);
        }//判断保存图片的文件夹是否存在 不存在就创建
        if (!file_exists(ROOT_PATH . 'public' . DS . $file . DS . $dir)) {
            $oldUMask = umask(0);
            mkdir(ROOT_PATH . 'public' . DS . $file . DS . $dir, 0777);
            umask($oldUMask);
        }//移动临时图片到指定文件夹中
        move_uploaded_file($img_name, '.' . DS . $file . DS . $dir . DS . $save_name);
        return [
            'code' => config('t_code'),
            'data' => config('url') . DS . $file . DS . $dir . DS . $save_name
        ];
    }

    /**
     * session操作
     * @param $session_name
     * @param $id
     * @param $status
     */
    public static function changeSession($session_name, $status, $id)
    {
        $session = empty(session($session_name)) ? [] : session($session_name);//从session中获取已经存在的商会id
        if ($status == 1) {
            $session[$id] = $id;//满足条件将新的值加入数组
        } else {
            unset($session[$id]);//不满足条件 在数组中有这个值 将这个值删除
        }
        session($session_name, $session);//将新的数组存入session
    }

    /**
     * 校验页码数和排序
     * @param $page
     * @param $pre
     * @param $sortName
     * @param $sortType
     * @param $sort
     * @return array
     */
    public static function checkShow($page, $pre, $sortName, $sortType /*, $sort*/)
    {
        $res = self::checkPageAndPre($page, $pre);
        if ($res['code'] != config('t_code')) {
            return $res;
        }
//        $res = self::checkSortCondition($sortName, $sort, $sortType);
//        if ($res['code'] != config('t_code')) {
//            return $res;
//        }
        return ['code' => config('t_code')];
    }

    /**
     * 连接数组 转换为字符串
     * @param array $array | 要连接的数组
     * @param string $joiner | key value 连接符
     * @param string $connect | 间隔符
     * @param array $prefix | 前缀
     * @return string
     */
    public static function spliceWhereArray(array $array, $prefix = [], $joiner = ' ', $connect = ',')
    {
        if (empty($array)) {
            return '';
        }
        $str = '';
        $i = 0;
        foreach ($array as $k => $v) {
            $str = $str . ' ' . $prefix[$k] . '.' . $k . $joiner . $v . ' ' . $connect;
            ++$i;
        }
        $str = rtrim($str, $connect);
        return $str;
    }

    public static function getOrderNumber($title, $number, $str)
    {
        $str = str_shuffle($str);
        return $title . substr($str, 0, $number);
    }

    /**
     * 校验是否是整数
     * @param $number
     * @param $count
     * @return bool
     */
    public static function checkFloat($number, $count = 1)
    {
        if (!is_numeric($number)) {
            return false;
        }

        if (floor($number / $count) * $count < $number) {
            return false;
        }

        return true;
    }

    public static function getFees()
    {
        $res = Db::table('drh_admin_config')
            ->field([
                'value'
            ])->where([
                'name' => 'fees'
            ])->find();
        return $res['value'];
    }

    /**
     * 输出XML字符
     * @param array $array
     * @return string
     */
    public static function arrayToXml(array $array)
    {
        if (!is_array($array) || count($array) <= 0) {
            dump("数组数据异常！");
        }

        $xml = "<xml>";
        foreach ($array as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    public static function postXmlCurl($url, $xml, $second = 30, $post = TRUE)
    {
        $ch = curl_init();
        // 设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

        curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 严格校验
        // 设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        // post提交方式
        curl_setopt($ch, CURLOPT_POST, $post);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        // 运行curl
        $data = curl_exec($ch);
        // 返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            throw new\Exception("curl出错，错误码:", $error);
        }
    }


    public static function xmlToArray($xml = false)
    {
        //禁止引用外部xml实体
        if (!$xml) {
            $xml = file_get_contents('php://input');
        }
        if (!$xml) {
            //throw_exception ( "xml数据异常！" );
        }
        libxml_disable_entity_loader(true);
        $xml_string = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xml_string), true);
        return $val;
    }


    public static function ToUrlParams($array)
    {
        $buff = "";
        ksort($array);
        foreach ($array as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 获取星期数
     * @param $time
     * @return mixed
     */
    public static function week($time)
    {
        $week_array = array("7", "1", "2", "3", "4", "5", "6");
        return $week_array[date("w", $time)];
    }

    /**
     * 获取上周开始结束时间
     * @param $time
     * @return array
     */
    public static function getStarEndTime($time)
    {
        $week = self::week($time);
        $last_week_end = $time - $week * 3600 * 24;
        $last_week_end = strtotime(date('Y-m-d', $last_week_end));
        $last_week_start = $last_week_end - 6 * 3600 * 24;//上周一开始时间
        $last_week_end = $last_week_end + 3600 * 24;//上周末结束时间
        return ['start' => $last_week_start, 'end' => $last_week_end];
    }

    public static function getArea($address_district)
    {
        return Db::table('china_area a')
            ->join('china_area b', 'a.parent_id=b.id', 'left')
            ->join('china_area c', 'b.parent_id=c.id', 'left')
            ->field([
                'a.id district_id',
                'a.name district',
                'b.id municipal_id',
                'b.name municipal',
                'b.parent_id province_id',
                'c.name province'
            ])->where([
                'a.id' => $address_district['id'],
            ])->find();
    }

    public static function getConfig($name)
    {
        $res = Db::table('drh_admin_config')
            ->field([
                'value'
            ])->where([
                'name' => $name
            ])->find();
        return $res['value'];
    }

    /**
     * 获取数量
     * @param $where
     * @param $table
     * @return mixed
     */
    public static function total($where, $table)
    {
        $res = Db::table($table)
            ->field('count(*) count')
            ->where($where)
            ->find();

        return $res['count'];
    }


    public static function debug($tempType, $tempStr, $path_name)
    {
//        $log_name="./";
//
//        $c=file_exists($log_name);
//        if(!$c){
//            $oldumask=umask(0);
//            mkdir($log_name,0777);
//            umask($oldumask);
//        }
        $tempStr = date('Y-m-d H:i:s') . ' ' . $tempType . "\r\n" . $tempStr . "\r\n\r\n";
//        file_put_contents($log_name."log.txt",$tempStr);
//        $my_file = fopen($log_name.$path_name, "a");
        $my_file = fopen(LOG_PATH . $path_name, "a");
        fwrite($my_file, $tempStr);
        fclose($my_file);
    }

    public static function bankInfo($card)
    {
        $path = dirname(dirname(__DIR__)) . '/extend/bankList.php';
        $bankList = require_once("{$path}");
        $card_8 = substr($card, 0, 8);
        if (isset($bankList[$card_8])) {
            return ['code' => config('t_code'), 'msg' => $bankList[$card_8]];
        }
        $card_6 = substr($card, 0, 6);
        if (isset($bankList[$card_6])) {
            return ['code' => config('t_code'), 'msg' => $bankList[$card_6]];
        }
        $card_5 = substr($card, 0, 5);
        if (isset($bankList[$card_5])) {
            return ['code' => config('t_code'), 'msg' => $bankList[$card_5]];
        }
        $card_4 = substr($card, 0, 4);
        if (isset($bankList[$card_4])) {
            return ['code' => config('t_code'), 'msg' => $bankList[$card_4]];
        }
        return ['code' => config('f_code'), 'msg' => '该卡号信息暂未录入'];
    }


    public static function http_curl($url)
    {
        //$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."";
        $ch = curl_init();
        //忽略安全检测
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //设置请求路径
        curl_setopt($ch, CURLOPT_URL, $url);
        //将请求的结果在最后curl_exec（）的时候赋值
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //有个头不可见
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $output = curl_exec($ch);
        if ($output === FALSE) {
            echo "CURL Error:" . curl_error($ch);
        }
        $output = json_decode($output, true);
        curl_close($ch);
        return $output;
    }

    public static function addMsg($id, $type, $time, $msg, $additional_mgs)
    {
        return Db::table('drh_msg')
            ->insertGetId([
                'user_id' => $id,
                'type_status' => $type,
                'msg' => $msg,
                'additional_mgs' => $additional_mgs,
                'create_time' => $time
            ]);
    }

    /**
     * 校验身份证
     * @param $value
     * @return bool
     */
    public static function validateIdCard($value)
    {
        if (!preg_match('/^\d{17}[0-9xX]$/', $value)) { //基本格式校验
            return false;
        }

        $parsed = date_parse(substr($value, 6, 8));
        if (!(isset($parsed['warning_count'])
            && $parsed['warning_count'] == 0)
        ) { //年月日位校验
            return false;
        }

        $base = substr($value, 0, 17);

        $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

        $tokens = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

        $checkSum = 0;
        for ($i = 0; $i < 17; $i++) {
            $checkSum += intval(substr($base, $i, 1)) * $factor[$i];
        }

        $mod = $checkSum % 11;
        $token = $tokens[$mod];

        $lastChar = strtoupper(substr($value, 17, 1));

        return ($lastChar === $token); //最后一位校验位校验
    }

    public static function PostUrl($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);//地址
        curl_setopt($ch, CURLOPT_POST, 1);//请求方式为post
        curl_setopt($ch, CURLOPT_HEADER, 0);//不打印header信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//返回结果转成字符串
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//post传输的数据。
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }

    public static function arrayValueChange($data, $value)
    {
        foreach ($data as $k => $v) {
            $data[$k][$value] = json_decode($v[$value])??unserialize($v[$value])??$v[$value];
        }
        return $data;
    }

    public static function checkGoodsAttr($goods_attr_value, $goods_attr)
    {


        $attr = explode('-', $goods_attr);

        $one = explode(',', $goods_attr_value['one']);
        $two = explode(',', $goods_attr_value['two']);

        $count_one = count($one);
        $count_two = count($two);
        $count_attr = count($attr);
        if (!empty($two[0]) && $count_attr == 1) {
            return -2;
        }
        $money = 0;
        $flag = false;
        for ($i = 0; $i < $count_one; $i++) {
            $one_attr = explode('-', $one[$i]);

            if ($one_attr[0] == $attr[0]) {
                $flag = true;
                $money += $one_attr[1];

            }
        }
        if (!$flag) {

            return -1;
        }
        if ($count_attr == 1) {
            return $money;
        }
        $flag = false;
        for ($i = 0; $i < $count_two; $i++) {
            $two_attr = explode('-', $two[$i]);
            if ($two_attr[0] == $attr[1]) {
                $flag = true;
                $money += $two_attr[1];
            }
        }
        if (!$flag) {
            return -1;
        }

        return $money;
    }

    public static function checkShopOrGoodsPlugin($shop_id, $goods_id, $arr = ['distribution_status', 'bargain_status'])
    {
        if (!empty($shop_id)) {
            $shop_plugin = self::getTableValue('drh_shop_plugin', ['distribution_status', 'bargain_status',
                'group_buy_status', 'game_status'], 'shop_id', $shop_id);

            if (!empty($shop_plugin)) {
                foreach ($arr as $k => $v) {
                    if ($shop_plugin[$v] < 1) {
                        return ['code' => 400, 'msg' => '该功能没有开启'];
                    }
                }
            }
        }
        if (!empty($goods_id)) {
            $goods_plugin = self::getTableValue('drh_goods_plugin', ['distribution_status', 'bargain_status',
                'group_buy_status', 'game_status'], 'goods_id', $goods_id);
            if (!empty($goods_plugin)) {
                foreach ($arr as $k => $v) {
                    if ($goods_plugin[$v] < 1) {
                        return ['code' => 400, 'msg' => '该功能没有开启'];
                    }
                }
            }
        }
        return ['code' => 200];
    }
    public static function db_count($field,$name,$db_table,$where=""){
        if($where === ""){
            return Db::query("SELECT $field ".$name." FROM ".$db_table);
        }else{
            return Db::query("SELECT $field ".$name." FROM ".$db_table." WHERE ".$where);
        }
    }
    public static function db_insert($table,$data){
        return Db::table($table)->insertGetId($data);
    }
    public static function db_upload($table,$where){
        return Db::execute("UPDATE  ".$table." SET ".$where);
    }
    public static function db_count_id($field,$name,$db_table,$where=""){
        $filed = str_replace("`","",$name);
        if($where === ""){
            return Db::query("SELECT $field ".$name." FROM ".$db_table)[0][$filed]??0;
        }else{
            return Db::query("SELECT $field ".$name." FROM ".$db_table." WHERE ".$where)[0][$filed]??0;
        }
    }
    //二维数组求和
    public static function summation($arr,$field){
        return array_sum(array_column($arr,$field));
    }
    //二维转一维
    public static function er_array($data){
        if($data !== array()){
            foreach ($data as $key=>$val){
                foreach ($val as $k=>$v){
                    $date[] = $v;
                }
            }
        }else{
            $date = array();
        }
        return $date;
    }
    /*
     *   getTime('Y');        //当前年的时间戳
     *   getTime('m');        //当前月的时间戳
     *   getTime('d');        //当前日的时间戳
     *   getTime('Y',true);    //明年的时间戳
     *   getTime('m',true);    //下月的时间戳
     *   getTime('d',true);    //明日的时间戳
     *   getTime();            //当前的时间戳
     * */
    public static function getTime($Ymd=NULL,$xia=false){
        if($Ymd=='Y' && $xia==true){
            //取下个年度开始时间戳
            return strtotime((date('Y',time())+1).'-01-01 00:00:00');
        }
        else if($Ymd=='Y'){
            //取本年度开始时间戳
            return strtotime(date('Y',time()).'-01-01 00:00:00');
        }
        else if($Ymd=='m' && $xia==true){
            //取下个月度开始时间戳
            $xiayue_nianfen    =    date('Y',time());
            $xiayue_yuefen    =    date('m',time());
            if($xiayue_yuefen==12){
                $xiayue_nianfen    +=    1;    //如果月份等于12月，那么下月年份+1
                $xiayue_yuefen    =    1;    //如果月份等于12月，那么下月月份=1月
            }
            else{
                $xiayue_yuefen    +=    1;    //如果月份不是12月，那么在当前月份上+1
            }
            return strtotime($xiayue_nianfen.'-'.$xiayue_yuefen.'-01 00:00:00');
        }
        else if($Ymd=='m'){
            //取本月度开始时间戳
            return strtotime(date('Y-m',time()).'-01 00:00:00');
        }
        else if($Ymd=='d' && $xia==true){
            //取明日开始时间戳
            return strtotime(date('Y-m-d',time()).' 00:00:00')+86400;
        }
        else if($Ymd=='d'){
            //取今日开始时间戳
            return strtotime(date('Y-m-d',time()).' 00:00:00');
        }
        else{
            //取当前时间戳
            return time();
        }
    }
    //查询供货商商品库存
    public static function attr_val($arr,$val){
        foreach ($val as $k=>$v){
            foreach ($arr as $key=>$va){
                if(!empty($v[$va])){
                    $val =$v[$va];
                }
            }
        }
        return $val;
    }
    //减少供货商商品库存
    public static function attr_val_number($arr,$val,$num){
        foreach ($arr as $k=>$v){
            foreach ($val as $key=>$va){
                if(!empty($val[$v])){
                    $val[$v]['stock'] = bcsub($va['stock'],$num);
                }
            }
        }
        return serialize($val);
    }
}